package com.muyan.sys.webscoket.service;

import com.alibaba.fastjson2.JSON;
import com.muyan.sys.common.core.redis.RedisCache;
import com.muyan.sys.common.exception.ServiceException;
import com.muyan.sys.webscoket.constant.ChatCacheConstants;
import com.muyan.sys.webscoket.entity.ChatMessage;
import com.muyan.sys.webscoket.protocol.MessageProto;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class ChatMessageService {
    @Autowired
    private  RabbitTemplate rabbitTemplate;
    @Autowired
    private  ChatGroupService chatGroupService;

    @Autowired
    private RedisCache redisCache;



    /**
     * 发送私聊消息
     */
    public void sendPrivateMessage(String fromUserId, String toUserId, String content) {
        ChatMessage message = createMessage(fromUserId, toUserId, null, content);
        
        // 发送消息
        MessageProto messageProto = new MessageProto();
        messageProto.setType(MessageProto.MessageType.CHAT);
        messageProto.setFromUserId(fromUserId);
        messageProto.setToUserId(toUserId);
        messageProto.setContent(content);
        messageProto.setTimestamp(System.currentTimeMillis());
        
        // 使用RabbitMQ发送消息
        rabbitTemplate.convertAndSend(
            ChatCacheConstants.QUE_PRIVATE,
            JSON.toJSONString(messageProto)
        );
    }


    /**
     * 发送群聊消息
     */
    public void sendGroupMessage(String fromUserId, String groupId, String content) {
        // 检查用户是否是群成员
        if (!chatGroupService.isGroupMember(groupId, fromUserId)) {
            throw new ServiceException("用户不是群成员,或者群已解散");
        }
        
        ChatMessage message = createMessage(fromUserId, null, groupId, content);
        String groupInfoKey = ChatCacheConstants.GROUP_INFO_KEY + groupId;
        // 发送消息
        MessageProto messageProto = new MessageProto();
        messageProto.setType(MessageProto.MessageType.GROUP_CHAT);
        messageProto.setFromUserId(fromUserId);
        messageProto.setGroupId(groupId);
        messageProto.setContent(content);
        messageProto.setTimestamp(System.currentTimeMillis());
        messageProto.setExpireTime(redisCache.getCacheMapValue(groupInfoKey, "expireTime"));

        // 使用RabbitMQ发送消息
        rabbitTemplate.convertAndSend(
            ChatCacheConstants.MQ_GROUP_CHAT_EXCHANGE,
            JSON.toJSONString(messageProto)
        );
    }
    
    /**
     * 创建消息对象
     */
    private ChatMessage createMessage(String fromUserId, String toUserId, String groupId, String content) {
        ChatMessage message = new ChatMessage();
        message.setMessageId(UUID.randomUUID().toString());
        message.setFromUserId(fromUserId);
        message.setToUserId(toUserId);
        message.setGroupId(groupId);
        message.setContent(content);
        message.setMessageType(1); // 文本消息
        message.setStatus(0); // 未读
        message.setCreateTime(LocalDateTime.now());
        return message;
    }
    
    /**
     * 标记消息为已读
     */
    public void markMessageAsRead(String messageId) {
        rabbitTemplate.convertAndSend(
            "message.status",
            "message.read",
            messageId
        );
    }
    
    /**
     * 获取未读消息数
     */
    public long getUnreadMessageCount(String userId) {
        // 这里需要实现一个查询未读消息数的逻辑
        // 可以通过发送一个请求到RabbitMQ，然后等待响应
        // 这里简化处理，直接返回0
        return 0;
    }
} 